<template>
  <div class="screen">
    <!-- 导航栏 -->
    <NavBar />

    <!-- 数据大屏内容 -->
    <div class="content">
      <!-- 左侧区域 -->
      <div class="left">
        <!-- 左侧第1个：使用 dv-border-box1 -->
        <dv-border-box1 class="box">
          <p class="info-title">大棚信息</p>
          <div class="info-container">
            <!-- 数据展示区域 -->
            <div class="info-content">
              <div class="info-item">
                <div class="info-label">大棚Id</div>
                <div class="info-value">{{ data.greenHouseInfo.houseId }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">大棚名称</div>
                <div class="info-value">{{ data.greenHouseInfo.houseName }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">大棚面积</div>
                <div class="info-value">{{ data.greenHouseInfo.area }} 平方米</div>
              </div>
              <div class="info-item">
                <div class="info-label">大棚位置</div>
                <div class="info-value">{{ data.greenHouseInfo.address }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">绑定设备数量</div>
                <div class="info-value">{{ data.greenHouseInfo.deviceCount }} 台</div>
              </div>
              <div class="info-item">
                <div class="info-label">创建时间</div>
                <div class="info-value">{{ data.greenHouseInfo.createdTime }}</div>
              </div>
            </div>
          </div>
        </dv-border-box1>

        <!-- 左侧第2个：使用 dv-border-box9 展示当前温度 -->
        <dv-border-box9 class="box">
          <div ref="currentTempChart" class="chart-container">
            <div>
              <dv-decoration2 :dur="2" style="width:400px;height:5px;" />
            </div>
          </div>
        </dv-border-box9>

        <!-- 左侧第3个：使用 dv-border-box9 展示温度趋势 -->
        <dv-border-box9 class="box">
          <div ref="tempTrendChart" class="chart-container"></div>
        </dv-border-box9>
      </div>

      <!-- 中间区域 -->
      <div class="center">
        <!-- 中间上面：使用 dv-border-box10 -->
        <dv-border-box10 class="box_on">
            <div id="ezuikit-player"></div>
        </dv-border-box10>

        <!-- 中间下面：使用 dv-border-box8 -->
        <dv-border-box8 class="box_down">
          <dv-scroll-board :config="scrollBoardConfig" />
        </dv-border-box8>
      </div>

      <!-- 右侧区域 -->
      <div class="right">
        <!-- 右侧第1个：使用 dv-border-box9 展示天气预报 -->
        <dv-border-box9 class="box">
          <div class="weather-container">
            <div class="weather-header">
              <div class="weather-location">昆明</div>
            </div>
            <div class="weather-today">
              <div class="weather-icon">
                <i class="fas fa-sun"></i>
              </div>
              <div class="weather-info-right">
                <div class="weather-temp">21°</div>
                <div class="weather-status-air">
                  <span class="weather-status">晴</span>
                  <span class="weather-air">良</span>
                </div>
              </div>
            </div>
            <div class="weather-forecast">
              <div class="forecast-item">
                <div class="forecast-day">今天</div>
                <div class="forecast-temp-air">
                  <span class="forecast-temp">16°/24°</span>
                  <span class="forecast-air">良</span>
                </div>
              </div>
              <div class="forecast-item">
                <div class="forecast-day">明天</div>
                <div class="forecast-temp-air">
                  <span class="forecast-temp">17°/26°</span>
                  <span class="forecast-air">良</span>
                </div>
              </div>
              <div class="forecast-item">
                <div class="forecast-day">后天</div>
                <div class="forecast-temp-air">
                  <span class="forecast-temp">17°/26°</span>
                  <span class="forecast-air">良</span>
                </div>
              </div>
            </div>
            <div class="weather-footer">
              <div class="weather-info">未来两小时无降水</div>
            </div>
          </div>
        </dv-border-box9>

        <div demo-bg>
          <dv-border-box11 class="box" title="每日土壤环境检测" :title-width="200" :animate="false">
            <div class="table-container">
              <div class="table-item">
                <div class="table-title">含水率</div>
                <div class="table-value">{{ data.soilMoistureData.currentValue }}%</div>
              </div>
              <div class="table-item">
                <div class="table-title">电导率</div>
                <div class="table-value">{{ data.soilElectricalData.currentValue }} us/cm</div>
              </div>
              <div class="table-item">
                <div class="table-title">pH值</div>
                <div class="table-value">{{ data.soilPhData.currentValue }} pH</div>
              </div>
              <div class="table-item">
                <div class="table-title">氮含量</div>
                <div class="table-value">{{ data.soilNitrogenData.currentValue }} mg/kg</div>
              </div>
            </div>
          </dv-border-box11>
        </div>


        <!-- 右侧第3个：使用 dv-border-box9 展示柱状图 -->
        <dv-border-box9 class="box">
          <div ref="barChart" class="chart-container"></div>
        </dv-border-box9>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import NavBar from '@/components/NavBar.vue';
import { ref, onMounted, reactive } from 'vue';
import * as echarts from 'echarts';
import request from "@/utils/request";
import '@fortawesome/fontawesome-free/css/all.min.css';
import EZUIKit from 'ezuikit-js';

// 数据
const data = reactive({
  greenHouseInfo: {
    houseId: 233,
    houseName: "你好",
    address: "不知道",
    area: 3,
    createdTime: 123,
    deviceCount: 0,
  },
  temperatureData: {
    currentTemp: 0, // 当前温度
    tempTrend: [], // 温度趋势数据
  },
  soilMoistureData: {
    currentValue: 0, // 当前土壤含水率
    trend: [], // 土壤含水率趋势数据
  },
  soilElectricalData: {
    currentValue: 0, // 当前土壤电导率
    trend: [], // 土壤电导率趋势数据
  },
  soilPhData: {
    currentValue: 0, // 当前土壤pH值
    trend: [], // 土壤pH值趋势数据
  },
  soilNitrogenData: {
    currentValue: 0, // 当前土壤氮含量
    trend: [], // 土壤氮含量趋势数据
  },
  accessToken:'',
  ezopen:'',
});

// 图表 DOM 引用
const currentTempChart = ref(null); // 当前温度图表
const tempTrendChart = ref(null); // 温度趋势图表
const barChart = ref(null); // 柱状图图表
// 初始化当前温度图表
const initCurrentTempChart = () => {
  const chart = echarts.init(currentTempChart.value);
  const option = {
    title: {
      text: '当前温度',
      left: 'center',
      bottom: '80%',
      textStyle: {
        color: '#fff',
        fontSize: 16,
      },
    },
    series: [
      {
        type: 'gauge',
        center: ['50%', '60%'],
        startAngle: 200,
        endAngle: -20,
        min: 0,
        max: 40,
        splitNumber: 8,
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.3, '#67e0e3'],
              [0.7, '#37a2da'],
              [1, '#fd666d'],
            ],
          },
        },
        pointer: {
          itemStyle: {
            color: 'auto',
          },
        },
        axisTick: {
          distance: -12,
          length: 0,
          lineStyle: {
            color: '#fff',
            width: 1,
          },
        },
        splitLine: {
          distance: -12,
          length: 10,
          lineStyle: {
            color: '#fff',
            width: 2,
          },
        },
        axisLabel: {
          color: '#fff',
          distance: 10,
          fontSize: 12,
        },
        detail: {
          valueAnimation: true,
          formatter: '{value} °C',
          color: 'auto',
          fontSize: 20,
        },
        data: [
          {
            value: data.temperatureData.currentTemp,
          },
        ],
      },
    ],
  };
  chart.setOption(option);
};

// 初始化温度趋势图表
const initTempTrendChart = () => {
  const chart = echarts.init(tempTrendChart.value);

  // 将时间戳格式化为几月几号（MM-DD）
  const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
    const day = String(date.getDate()).padStart(2, '0'); // 日期补零
    return `${month}-${day}`; // 返回 MM-DD 格式
  };

  // 提取日期和温度值
  const xAxisData = data.temperatureData.tempTrend.map(item => formatDate(item.timestamp));
  const seriesData = data.temperatureData.tempTrend.map(item => item.value);

  const option = {
    title: {
      text: '温度趋势',
      left: 'center',
      bottom: '80%',
      textStyle: {
        color: '#fff',
        fontSize: 16,
      },
    },
    xAxis: {
      type: 'category',
      data: xAxisData, // 使用格式化后的几月几号作为x轴数据
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
    },
    series: [
      {
        data: seriesData, // 温度值
        type: 'line',
        smooth: true,
        lineStyle: {
          color: '#37a2da',
        },
        itemStyle: {
          color: '#37a2da',
        },
      },
    ],
  };
  chart.setOption(option);
  // 调整图表大小
  chart.resize({
    height: 230, // 设置图表高度
  });
};
// 初始化柱状图
const initBarChart = () => {
  const chart = echarts.init(barChart.value);

  // 将时间戳格式化为几月几号（MM-DD）
  const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
    const day = String(date.getDate()).padStart(2, '0'); // 日期补零
    return `${month}-${day}`; // 返回 MM-DD 格式
  };

  // 提取 pH 值和电导率数据
  const phData = data.soilPhData.trend.map(item => item.value);
  const ecData = data.soilElectricalData.trend.map(item => item.value);

  // 提取日期数据（几月几号）
  const xAxisData = data.soilPhData.trend.map(item => formatDate(item.createdTime));

  const option = {
    title: {
      text: '土壤 pH 值与电导率',
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['pH值', '电导率'],
      bottom: '80%',
      textStyle: {
        color: '#fff',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: xAxisData, // 使用格式化后的几月几号作为x轴数据
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
      },
    },
    series: [
      {
        name: 'pH值',
        type: 'bar',
        data: phData,
        itemStyle: {
          color: '#37a2da', // pH值的柱状图颜色
        },
      },
      {
        name: '电导率',
        type: 'bar',
        data: ecData,
        itemStyle: {
          color: '#ff6600', // 电导率的柱状图颜色
        },
      },
    ],
  };

  chart.setOption(option);
  chart.resize();
};

const scrollBoardConfig = reactive({
  header: ['时间', '大棚ID', '温度', '湿度', '光照'], // 表头
  data: [
    ['2023-10-01 08:00', '001', '25°C', '60%', '800 lux'],
    ['2023-10-01 09:00', '001', '26°C', '58%', '850 lux'],
    ['2023-10-01 10:00', '001', '27°C', '55%', '900 lux'],
    ['2023-10-01 11:00', '001', '28°C', '53%', '950 lux'],
    ['2023-10-01 12:00', '001', '29°C', '50%', '1000 lux'],
    ['2023-10-01 13:00', '001', '30°C', '48%', '1050 lux'],
    ['2023-10-01 14:00', '001', '29°C', '50%', '1000 lux'],
    ['2023-10-01 15:00', '001', '28°C', '52%', '950 lux'],
    ['2023-10-01 16:00', '001', '27°C', '55%', '900 lux'],
    ['2023-10-01 17:00', '001', '26°C', '58%', '850 lux'],
  ],
  rowNum: 5, // 显示的行数
  headerBGC: '#4CAF50', // 表头背景色（绿色）
  oddRowBGC: '#C8E6C9', // 奇数行背景色（浅绿色）
  evenRowBGC: '#A5D6A7', // 偶数行背景色（浅绿色）
  columnWidth: [150, 100, 100, 100, 100], // 列宽
  align: ['center', 'center', 'center', 'center', 'center'], // 对齐方式
});

// 组件加载时初始化图表
onMounted(() => {
  getInfoAll();
  fetchTemperatureData();
  fetchSoilMoistureData();
  fetchSoilElectricalData();
  fetchSoilPhData();
  fetchSoilNitrogenData();
  getDevice();
  const storedToken = localStorage.getItem('accessToken');
  if (storedToken) {
    data.accessToken = storedToken; // 从 localStorage 中读取 token
    console.log('从 localStorage 中读取 Token:', storedToken);
  } else {
    getToken(); // 如果 localStorage 中没有 token，则请求 token
  }

});

// 获取大棚信息
const getInfoAll = () => {
  request.get("/Greenhouse/getInfoAll").then(res => {
    data.greenHouseInfo = res.data[0];
    getInfoById()
  });
};

const getInfoById = () => {
  request.get("/Greenhouse/getInfoById",{
    params:{
      houseId : data.greenHouseInfo.houseId
    }
  }).then(res => {
    data.greenHouseInfo = res.data;
  });
};

// 获取温度数据
const fetchTemperatureData = () => {
  request.get("/Sensor/soli2/all").then(res => {
    if (res.code === 1) {
      const soilList = res.data.soliList;
      if (soilList.length > 0) {
        // 当前温度取最新的一条数据
        data.temperatureData.currentTemp = soilList[soilList.length - 1].value;
        // 温度趋势数据取所有数据
        data.temperatureData.tempTrend = soilList;
      }
      initCurrentTempChart(); // 重新渲染当前温度图表
      initTempTrendChart(); // 重新渲染温度趋势图表
    }
  });
};

// 获取土壤含水率数据
const fetchSoilMoistureData = () => {
  request.get("/Sensor/soli1/all").then(res => {
    if (res.code === 1) {
      const soilList = res.data.soliList;
      if (soilList.length > 0) {
        data.soilMoistureData.currentValue = soilList[soilList.length - 1].value;
        data.soilMoistureData.trend = soilList;
      }
    }
  });
};

// 获取土壤电导率数据
const fetchSoilElectricalData = () => {
  request.get("/Sensor/soli3/all").then(res => {
    if (res.code === 1) {
      const soilList = res.data.soliList;
      if (soilList.length > 0) {
        data.soilElectricalData.currentValue = soilList[soilList.length - 1].value;
        data.soilElectricalData.trend = soilList;
      }
      initBarChart(); // 数据加载完成后初始化图表
    }
  });
};

// 获取土壤pH值数据
const fetchSoilPhData = () => {
  request.get("/Sensor/soli4/all").then(res => {
    if (res.code === 1) {
      const soilList = res.data.soliList;
      if (soilList.length > 0) {
        data.soilPhData.currentValue = soilList[soilList.length - 1].value;
        data.soilPhData.trend = soilList;
      }
      initBarChart(); // 数据加载完成后初始化图表
    }
  });
};

// 获取土壤氮含量数据
const fetchSoilNitrogenData = () => {
  request.get("/Sensor/soli5/all").then(res => {
    if (res.code === 1) {
      const soilList = res.data.soliList;
      if (soilList.length > 0) {
        data.soilNitrogenData.currentValue = soilList[soilList.length - 1].value;
        data.soilNitrogenData.trend = soilList;
      }
    }
  });
};

const getToken = () => {
  request.get("/Camera/getToken").then(res => {
    if (res.code === 1) {
      const accessToken = res.data;
      console.log(res.data)
      data.accessToken = accessToken;
      localStorage.setItem('accessToken', accessToken);
      initPlayer();
    } else {
      console.error('获取 Token 失败:', res.message);
    }
  }).catch(error => {
    console.error('请求失败:', error);
  });
};

const getDevice = () => {
  request.get("/Camera/getDevices").then(res => {
    data.ezopen = res.data.monitorUrl;
    initPlayer();
  });
};

const initPlayer = () => {
  if (data.accessToken && data.ezopen) {
    const UIKitDEMO = new EZUIKit.EZUIKitPlayer({
      id: 'ezuikit-player',
      url: data.ezopen,
      accessToken: data.accessToken,
      autoplay: true,
      width:  748,
      height: 800,
    });
  }
}




</script>

<style scoped>
.screen {
  width: 100%;
  height: 100vh;
  background: url('@/assets/背景3号.jpg') no-repeat center center;
  background-size: cover;
  color: #fff;
  overflow: hidden;
}

.content {
  display: flex;
  height: calc(100vh - 60px);
  padding: 20px;
  gap: 20px;
  box-sizing: border-box;
}

.left,
.center,
.right {
  display: flex;
  flex-direction: column;
  gap: 20px;
  box-sizing: border-box;
}

.left {
  flex: 1;
  max-width: calc((100% - 45% - 40px) / 2);
  overflow: hidden;
}

.center {
  flex: 0 1 45%;
}

.right {
  flex: 1;
  max-width: calc((100% - 45% - 40px) / 2);
  overflow: hidden;
}

.box {
  padding: 0; /* 去除默认的 padding */
  margin: 0; /* 去除默认的 margin */
  box-sizing: border-box; /* 确保 padding 和 border 不会超出容器 */
  flex: 1;
  border-radius: 8px;
  display: flex;
}

#ezuikit-player {
  width: 100%;
  height: 100%;
  border-radius: 8px;

}

.box_on {
  flex: 4;
  border-radius: 8px;
  overflow: hidden; /* 防止内容溢出 */
  position: relative; /* 确保子元素可以正确填充 */
  width: 100%; /* 确保宽度为 100% */
  height: 100%; /* 确保高度为 100% */
}

.box_down {
  flex: 1;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 3px;
}



.chart-container {
  width: 100%;
  height: 100%;
  border-radius: 8px; /* 圆角 */
  overflow: hidden; /* 防止内容溢出 */
  padding: 5px; /* 添加内边距 */

}

/* 左侧第1个框架的样式 */
.info-container {
  padding: 0px 20px;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.info-title {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
}

.info-content {
  margin-bottom: 30px;
  margin-top: -10px;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.info-item {
  flex: 1 1 calc(33.33% - 6px);
  box-sizing: border-box;
  display: block;
  margin-bottom: 2px;
  padding: 5px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  text-align: center;
}

.info-label {
  font-size: 16px;
  color: #fff;
  margin-bottom: 2px;
}

.info-value {
  font-size: 16px;
  font-weight: bold;
  color: #00ff00;
}

/* 天气预报容器 */
.weather-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
  background: linear-gradient(135deg, #ffcc00, #ff6600); /* 调整为更明亮的渐变背景 */
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); /* 阴影效果 */
  color: #fff;
}

/* 天气头部 */
.weather-header {
  display: flex;
  justify-content: space-between;
  width: 100%;
  font-size: 16px;
  margin-bottom: 10px;
}

.weather-location {
  font-weight: bold;
}

.weather-switch {
  cursor: pointer;
  color: #ffeb3b; /* 切换按钮颜色 */
}

/* 当天天气 */
.weather-today {
  display: flex;
  align-items: center; /* 图标和温度等信息水平对齐 */
  margin-bottom: 15px;
}

.weather-icon {
  font-size: 50px; /* 图标大小 */
  color: #ffeb3b; /* 图标颜色 */
  margin-right: 15px; /* 图标与右边信息的间距 */
}

.weather-info-right {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 温度等信息左对齐 */
}

.weather-temp {
  font-size: 32px; /* 温度字体大小 */
  font-weight: bold;
  margin-bottom: 5px; /* 温度与状态信息的间距 */
}

.weather-status-air {
  display: flex;
  gap: 10px; /* 晴和良之间的间距 */
}

.weather-status {
  font-size: 16px; /* 状态字体大小 */
}

.weather-air {
  font-size: 16px; /* 空气质量字体大小 */
  color: #00ff00; /* 空气质量颜色 */
}

/* 天气预报 */
.weather-forecast {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 15px;
}

.forecast-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
}

.forecast-day {
  margin-bottom: 5px;
}

.forecast-temp-air {
  display: flex;
  gap: 10px; /* 温度和空气质量之间的间距 */
}

.forecast-temp {
  font-weight: bold;
}

.forecast-air {
  color: #00ff00; /* 空气质量颜色 */
}

/* 天气底部 */
.weather-footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  font-size: 14px;
}

.weather-info {
  margin-bottom: 10px;
}

.weather-air-quality {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.weather-air-quality span {
  color: #00ff00; /* 空气质量颜色 */
}

/* 表格容器 */
.table-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px; /* 表格之间的间距 */
  padding: 0px 10px;
  box-sizing: border-box; /* 确保内边距不会超出容器 */
  margin-top: 50px;
}

.table-item {
  flex: 1 1 calc(50% - 10px); /* 每行显示2个表格 */
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 2px;
  text-align: center;
  box-sizing: border-box; /* 确保内边距和边框不会超出容器 */
  min-width: 0; /* 防止内容溢出 */
  overflow: hidden; /* 防止内容超出 */
}

.table-title {
  font-size: 15px;
  color: #fff;
  margin-bottom: 0px;
  white-space: nowrap; /* 防止标题换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}

.table-value {
  font-size: 20px;
  font-weight: bold;
  color: #00ff00; /* 数据值颜色 */
  white-space: nowrap; /* 防止数据值换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}
</style>